import {
  LocalizationContext,
  PdfJs,
  SpecialZoomLevel,
  Spinner,
} from "../../core";

import BookmarkList from "./BookmarkList";
import { FC, useContext, useEffect, useState } from "react";

interface BookmarkLoaderProps {
  doc: PdfJs.PdfDocument;
  onJumpToDest(
    pageIndex: number,
    bottomOffset: number,
    scaleTo: number | SpecialZoomLevel
  ): void;
}
interface BookmarkState {
  isLoaded: boolean;
  items: PdfJs.Outline[];
}

const BookmarkLoader: FC<BookmarkLoaderProps> = ({ doc, onJumpToDest }) => {
  const l10n = useContext(LocalizationContext);
  const [bookmarks, setBookmarks] = useState<BookmarkState>({
    isLoaded: false,
    items: [],
  });

  useEffect(() => {
    setBookmarks({
      isLoaded: false,
      items: [],
    });
    doc.getOutline().then((outline) => {
      setBookmarks({
        isLoaded: true,
        items: outline || [],
      });
    });
  }, [doc]);

  return !bookmarks.isLoaded ? (
    <Spinner />
  ) : bookmarks.items.length === 0 ? (
    <div className="rpv-bookmark__empty">
      {l10n && l10n.bookmark
        ? l10n.bookmark.noBookmark
        : "There is no bookmark"}
    </div>
  ) : (
    <div className="rpv-bookmark__container">
      <BookmarkList
        bookmarks={bookmarks.items}
        depth={0}
        doc={doc}
        onJumpToDest={onJumpToDest}
      />
    </div>
  );
};

export default BookmarkLoader;
